package com.zq.it.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.util.FileCopyUtils;

import com.opensymphony.xwork2.ActionSupport;
import com.zq.it.service.FileSourceService;
import com.zq.it.service.admin.ClassService;
import com.zq.it.service.admin.StudentService;
import com.zq.it.service.admin.TeacherService;
import com.zq.it.service.exam.CourseWareService;
import com.zq.it.service.exam.ExamService;
import com.zq.it.service.exam.PaperService;
import com.zq.it.service.exam.QuestionService;
import com.zq.it.service.exam.TaskService;
import com.zq.it.tool.Constant;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class BaseAction extends ActionSupport
		implements
			ServletRequestAware,
			ServletResponseAware,
			ServletContextAware {

	private static final long serialVersionUID = 1L;
	private HttpServletRequest request = null;
	private HttpServletResponse response = null;
	private ServletContext servletContext = null;
	// 单个文件属性获取
	private File upload;
	private String uploadFileName;
	private String uploadContentType;
	private Integer id;

	// 多个文件属性

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}

	private List<File> file;
	public List<File> getFile() {
		return file;
	}
	public void setFile(List<File> file) {
		this.file = file;
	}
	public List<String> getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(List<String> fileFileName) {
		this.fileFileName = fileFileName;
	}
	public List<String> getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(List<String> fileContentType) {
		this.fileContentType = fileContentType;
	}

	private List<String> fileFileName;
	private List<String> fileContentType;

	// iocע��
	public HttpServletResponse getResponse() {
		return response;
	}
	public HttpSession getHttpSession() {
		return getRequest().getSession();
	}
	protected void uploadFile(String _dir, String fileName, File file)
			throws Exception {
		try {
			if (null == file)
				return;
			InputStream in = new FileInputStream(file);
			String dir = getRealPath(_dir);
			File saveDir = new File(dir);
			if (!saveDir.exists()) {
				saveDir.mkdirs();
			}
			File uploadFile = new File(dir, fileName);
			OutputStream out = new FileOutputStream(uploadFile);
			FileCopyUtils.copy(in, out);
		} catch (Exception e) {
			throw e;
		}
	}
	public void uploadList(String name, List<?> list) {
		HttpSession session = getHttpSession();
		if (session.getAttribute(name) != null)
			session.removeValue(name);
		session.setAttribute(name, list);
	}

	public void saveListToRequest(String name, Object obj) {
		HttpServletRequest request = getRequest();
		if (request.getAttribute(name) != null)
			request.removeAttribute(name);
		request.setAttribute(name, obj);
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static String getMistiming(Date currenTime,int calendarType, int value, SimpleDateFormat dateFormat) throws ParseException {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(currenTime);
		calendar.add(calendarType, value);
		Date nowDate = dateFormat.parse(dateFormat.format(calendar.getTime()));	
		return dateFormat.format(nowDate);
	}


	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	protected void deleteFile(String path) {
		path = getRealPath(path);
		File temp = new File(path);
		if (temp.isFile()) {
			temp.delete();
		}
	}
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	public HttpServletRequest getRequest() {
		return request;
	}

	public String toJSON(Object object) {
		return JSONArray.fromObject(object).toString();
	}

	public void print(String message, String encoding,
			String servletContentType) {
		try {
			if (response != null) {
				response.setCharacterEncoding(encoding);
				response.setContentType(servletContentType);
				response.getWriter().write(message);
				response.getWriter().flush();
			}
		} catch (IOException e) {
			System.err.println(e);
		} finally {
			try {
				response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	/**
	 * 得到绝对路径
	 * 
	 * @param parentUTL:父路径
	 * 
	 */
	public String getRealPath(String path) {
		return servletContext.getRealPath(path);
	}
	// 得到相对项目的路径
	public URL getSourcePath(String source) {
		URL url = null;
		try {
			url = servletContext.getResource(source);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			url = null;
		}
		return url;
	}

	/**
	 * @param uploadFile
	 *            :上传的文件
	 * @param saveFileURL
	 *            ：新文件路径
	 * @throws IOException
	 */
	protected boolean upLoad(File uploadFile, String saveFileURL) {

		try {
			InputStream is = new FileInputStream(uploadFile);
			File destFile = new File(saveFileURL);
			OutputStream os = new FileOutputStream(destFile);
			byte[] b = new byte[1024 * 1024 * 10];
			int length = 0;
			while (true) {
				length = is.read(b);
				if (length < 0)
					break;
				os.write(b, 0, length);
			}
			os.flush();
			is.close();
			os.close();
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	protected String json(Map<String, Object> data) {
		JSONObject jsonObject = new JSONObject();
		for (Map.Entry<String, Object> entry : data.entrySet()) {
			jsonObject.accumulate(entry.getKey(), entry.getValue());
		}
		return jsonObject.toString();
	}

	protected String json(Object data) {
		return JSONObject.fromObject(data).toString();
	}

	protected void print_json_utf8(String data) throws IOException {
		print_json(data, "UTF-8");
	}

	protected void print_xml_utf8(String data) throws IOException {
		print_xml(data, "UTF-8");
	}

	protected void print_html_utf8(String data) throws IOException {
		print_html(data, "UTF-8");
	}

	protected void print_json(String data, String encoding) throws IOException {
		print(data, encoding, "application/json");
	}

	protected void print_xml(String data, String encoding) throws IOException {
		print(data, encoding, "text/xml");
	}

	protected void print_html(String data, String encoding) throws IOException {
		print(data, encoding, "text/html");
	}

	protected void print_text_utf8(String data) throws IOException {
		print_text(data, "UTF-8");
	}

	protected void print_text(String data, String encoding) throws IOException {
		print(data, encoding, "text/plain");
	}

	/*
	 * private void setContentType(String encoding, String contentType) {
	 * response.setContentType(contentType + "; charset=" + encoding); }
	 */

	// 导出Excel表
	protected void download(InputStream in, String fileName) {
		// System.out.println(fileName);
		OutputStream out = null;
		try {
			int length = in.available();
			response.setCharacterEncoding("application/force-download");
			response.setHeader("Content-Length", String.valueOf(length));
			fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=\"" + Constant.toUtf8String(fileName));
			out = response.getOutputStream();
			FileCopyUtils.copy(in, out);
		} catch (Exception e) {
		} finally {
			try {
				if (null != in) {
					in.close();
					in = null;
				}
				if (null != out) {
					out.flush();
					out.close();
					out = null;
				}
			} catch (Exception e) {

			}
		}
	}
	protected void download(String fileName, String path) {
		OutputStream out = null;
		InputStream in = null;
		try {
			in = getServletContext().getResourceAsStream(path);
			int length = in.available();
			response.setCharacterEncoding("application/force-download");
			response.setHeader("Content-Length", String.valueOf(length));
			fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=\"" + fileName + "\" ");
			out = response.getOutputStream();
			FileCopyUtils.copy(in, out);
		} catch (Exception e) {

		} finally {
			try {
				if (null != in) {
					in.close();
					in = null;
				}
				if (null != out) {
					out.flush();
					out.close();
					out = null;
				}
			} catch (Exception e) {
				// 蹇界暐
			}
		}
	}
	
	
	protected void downloadTask(String fileName, String path) {
		OutputStream out = null;
		InputStream in = null;
		try {
			in = new FileInputStream(new File(path, fileName));
			int length = in.available();
			response.setCharacterEncoding("application/force-download");
			response.setHeader("Content-Length", String.valueOf(length));
			fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=\"" + fileName + "\" ");
			out = response.getOutputStream();
			FileCopyUtils.copy(in, out);
		} catch (Exception e) {

		} finally {
			try {
				if (null != in) {
					in.close();
					in = null;
				}
				if (null != out) {
					out.flush();
					out.close();
					out = null;
				}
			} catch (Exception e) {
				// 蹇界暐
			}
		}
	}
	
	protected ServletContext getServletContext() {
		if (null == servletContext) {
			return ServletActionContext.getServletContext();
		}
		return servletContext;
	}

	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	private int selectedNum = 1; // 分页号码
	private String pageStr;
	public String getPageStr() {
		return pageStr;
	}

	public void setPageStr(String pageStr) {
		this.pageStr = pageStr;
	}

	public int getSelectedNum() {
		return selectedNum;
	}

	public void setSelectedNum(int selectedNum) {
		this.selectedNum = selectedNum;
	}

	public void setPage(String requestURL, int totalPage, Integer type,
			String time) {
		String type_str = type == null ? "" : type.toString();
		String time_str = time == null ? "" : time;
		String first_str = "<div class=\"page\">";
		String str1_3 = "<a href=" + requestURL + "?selectedNum=1&time="
				+ time_str + "&type=" + type_str + ">1</a><a href=" + requestURL
				+ "?selectedNum=2&time=" + time_str + "&type=" + type_str
				+ ">2</a><a href=" + requestURL + "?selectedNum=3&time="
				+ time_str + "&type=" + type_str + ">3</a>";
		String str_last1_2 = "<a href=" + requestURL + "?selectedNum="
				+ (totalPage - 1) + "&time=" + time_str + "&type=" + type_str
				+ ">" + (totalPage - 1) + "</a><a href=" + requestURL
				+ "?selectedNum=" + totalPage + "&time=" + time_str + "&type="
				+ type_str + ">" + totalPage + "</a>";
		String str_next = "<a href=" + requestURL + "?selectedNum="
				+ (selectedNum + 1) + "&time=" + time_str + "&type=" + type_str
				+ "><b class=\"next\">下页</b></a></div>";
		String str_for = "<a href=" + requestURL + "?" + (selectedNum - 1)
				+ "&time=" + time_str + "&type=" + type_str
				+ "><b class=\"next\">上页</b></a>";

		if (totalPage > 7) {

			if (selectedNum == 1) {
				setPageStr(first_str + str1_3 + "…" + str_last1_2 + str_next);
			} else if (selectedNum > 1 && selectedNum < 5) {

				setPageStr(first_str + str_for + str1_3 + "<a href="
						+ requestURL + "?selectedNum=4&time=" + time_str
						+ "&type=" + type_str + ">4</a>" + "<a href="
						+ requestURL + "?selectedNum=5&time=" + time_str
						+ "&type=" + type_str + ">5</a>" + "<a href="
						+ requestURL + "?selectedNum=6&time=" + time_str
						+ "&type=" + type_str + ">6</a>" + str_next + "…"
						+ str_last1_2 + "</div>");

			} else if (selectedNum > 4 && selectedNum < totalPage - 3) {
				setPageStr(first_str + str_for + str1_3 + "…" + "<a href="
						+ requestURL + "?selectedNum=" + (selectedNum - 1)
						+ "&time=" + time_str + "&type=" + type_str + ">"
						+ (selectedNum - 1) + "</a>" + "<a href=" + requestURL
						+ "?selectedNum=" + selectedNum + "&time=" + time_str
						+ "&type=" + type_str + ">" + selectedNum + "</a>"
						+ "<a href=" + requestURL + "?selectedNum="
						+ (selectedNum + 1) + "&time=" + time_str + "&type="
						+ type_str + ">" + (selectedNum + 1) + "</a>" + "…"
						+ str_last1_2 + str_next);
			} else if (selectedNum > totalPage - 4 && selectedNum < totalPage) {
				setPageStr(first_str + str_for + str1_3 + "…" + str_last1_2
						+ str_next);
			} else if (selectedNum == totalPage) {
				setPageStr(first_str + str_for + str1_3 + "…" + "<a href="
						+ requestURL + "?selectedNum=" + (totalPage - 4)
						+ "&time=" + time_str + "&type=" + type_str + ">"
						+ (totalPage - 4) + "</a>" + "<a href=" + requestURL
						+ "?selectedNum=" + (totalPage - 3) + "&time="
						+ time_str + "&type=" + type_str + ">" + (totalPage - 3)
						+ "</a>" + "<a href=" + requestURL + "?selectedNum="
						+ (totalPage - 2) + "&time=" + time_str + "&type="
						+ type_str + ">" + (totalPage - 2) + "</a>" + "<a href="
						+ requestURL + "?selectedNum=" + (totalPage - 1)
						+ "&time=" + time_str + "&type=" + type_str + ">"
						+ (totalPage - 1) + "</a>" + "<a href=" + requestURL
						+ "?selectedNum=" + totalPage + "&time=" + time_str
						+ "&type=" + type_str + ">" + totalPage + "</a>"
						+ "</div>");
			}

		} else {
			for (int i = 1; i <= totalPage; i++) {
				first_str += "<a href=" + requestURL + "?selectedNum=" + i
						+ "&time=" + time_str + "&type=" + type_str + ">" + i
						+ "</a>";
			}
			setPageStr(first_str + "</div>");

		}
	}

	private int number = 1;
	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}
	protected String makeFileName(String path, String fileName) {
		path = getRealPath(path) + "\\";
		File file = new File(path + fileName);
		if (file.isFile()) {
			fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "("
					+ 1 + ")" + fileName.substring(fileName.lastIndexOf("."),
							fileName.length());
		} else {
			return fileName;
		}
		for (int i = 2;; i++) {
			file = new File(path + fileName);
			if (file.isFile()) {
				fileName = fileName.substring(0, fileName.lastIndexOf("("))
						+ "(" + i + ")" + fileName.substring(
								fileName.lastIndexOf("."), fileName.length());
			} else {
				break;
			}
		}
		return fileName;
	}
	public int getTotalSize() {
		return totalSize;
	}

	public void setTotalSize(int totalSize) {
		this.totalSize = totalSize;
	}

	private int totalSize = 0;
	private int totalPage = 1;
	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	@Resource
	protected FileSourceService fileSourceService;
	@Resource
	protected TeacherService teacherService;
	@Resource
	protected ClassService classService;
	@Resource
	protected TaskService taskService;
	@Resource
	protected CourseWareService courseWareService;
	@Resource
	protected QuestionService questionService;
	@Resource
	protected StudentService studentService;
	@Resource
	protected PaperService paperService;
	@Resource
	protected ExamService examService;
	protected int page;

	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	
	private String account;
	private String password;

	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	

}
